const { ccclass, property } = cc._decorator;

/**
 * http通讯
 */
@ccclass
export default class Http {
    //单例
    private static _ins: Http;
    //请求地址
    private static _url: string = "http://192.168.1.100:8080";
    public static get ins(): Http {
        if (this._ins == null) {
            this._ins = new Http();
        }
        return this._ins;
    }
    public token: string = "";
    public Authorization: string = "Authorization";
    public prefix: string = "";
    public constructor() {

    }
    public jsonToQueryString(json: any) {
        var str = '';
        if (typeof json == "object") {
            str = "?";
            for (var k in json) {
                if (str != "?") {
                    str += "&";
                }
                str += k + "=" + json[k];
            }
        }
        return str;
    }
    private objectToFormData(obj: Object): FormData {
        const formData = new FormData();
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                const value = obj[key];
                if (Array.isArray(value)) {
                    for (const item of value) {
                        formData.append(key, item);
                    }
                } else {
                    formData.append(key, value);
                }
            }
        }
        return formData;
    }
    private async quest(xhr: XMLHttpRequest, method: "GET" | "POST" | "PUT" = "GET", data: Object, formData: boolean = false) {
        return new Promise((resolve, reason) => {
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // console.log("[Http] 返回", xhr.response);
                        resolve(JSON.parse(xhr.response));
                    } else {
                        console.log("[Http] 返回", xhr.response);
                        reason(xhr.status)
                    }
                }
            };
            xhr.onerror = (error) => {
                console.error("http request onerror", error);
                reason(error)
            };
            xhr.ontimeout = (e) => {
                console.error("http request timeout", e);
                reason(e)
            }
            //根据POST和GET方式，选择是否发送msg数据
            if (formData) {
                xhr.send(this.objectToFormData(data));
            } else {
                if (method == 'POST') {
                    xhr.send(JSON.stringify(data));
                } else if (method == 'PUT') {
                    xhr.send(JSON.stringify(data));
                } else {
                    xhr.send();
                }
            }
        });
    }
    public async api(path: string, data: any, method: "GET" | "POST" | "PUT" = "GET", bLock: boolean = false, isFormData: boolean = false) {
        let url = Http._url + path;
        // console.log("[Http] 请求Url:",url, " 方式:", method, " 数据:", data);
        bLock && this.lock();
        var xhr = new XMLHttpRequest();
        xhr.timeout = 20000;
        // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if (cc.sys.isNative) {
        // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // }
        // xhr.setRequestHeader('authorization', Config.TOKEN);
        //发送数据
        if (method == 'GET') {
            url = url + encodeURI(this.jsonToQueryString(data));
            xhr.open(method, url, true);
            if (cc.sys.isNative) {
                xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
                xhr.setRequestHeader("content-type", "text/html;charset=utf-8");
            }
        } else {
            xhr.open(method, url, true);
            xhr.setRequestHeader("Content-type", "application/json");
        }
        // xhr.setRequestHeader('Authorization', "Bearer " + Config.TOKEN);
        xhr.setRequestHeader(this.Authorization, this.prefix+this.token);
        let self = this;
        return new Promise((resolve, reason) => {
            self.quest(xhr, method, data, isFormData).then(value => {
                bLock && self.unlock();
                resolve(value);
            }).catch(err => {
                bLock && self.unlock();
                resolve(null);
            });
        });
    }
    /**
     * 发送请求
     * @param url 接口地址
     * @param data 消息字符串 (json格式)
     * @param method 请求方式
     * @param bLock 是否锁定屏幕
     * @param formData 是否formData
     * @returns 
     */
    public async send(url: string, data: any, method: "GET" | "POST" | "PUT" = "GET", bLock: boolean = false, formData: boolean = false) {
        // console.log("[Http] 请求Url:",url, " 方式:", method, " 数据:", data);
        bLock && this.lock();
        var xhr = new XMLHttpRequest();
        xhr.timeout = 10000;
        if (method == 'GET') {
            url = url + encodeURI(this.jsonToQueryString(data));
            xhr.open(method, url, true);
            if (cc.sys.isNative) {
                xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
                xhr.setRequestHeader("content-type", "text/html;charset=utf-8");
            }
        } else {
            xhr.open(method, url, true);
            xhr.setRequestHeader("Content-type", "application/json");
        }
        let self = this;
        return new Promise((resolve, reason) => {
            self.quest(xhr, method, data, formData).then(value => {
                bLock && self.unlock();
                resolve(value);
            }).catch(err => {
                bLock && self.unlock();
                resolve(null);
            });
        });

    }
    /**解锁屏幕 */
    private unlock() {
        // LockScreenUI.ins.unShowloading();
        // if (Config.loading) {
        //     Config.loading.hide2();
        // }

    }

    /**锁屏 */
    private lock() {
        // if (Config.loading) {
        //     Config.loading.show2();
        // }

        // LockScreenUI.ins.Showloading('网络加载中请稍后...');
    }
}
